// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package trace_dao

import (
	"strings"
	"time"

	"gitcode.com/opendragonfly/df_proto_gen_go.git/trace_api"
	"github.com/dgraph-io/badger/v4"
	"google.golang.org/protobuf/proto"
)

const (
	_SIMPLE_TRACE_NAME_SPACE = "simpleTrace"
)

type _SimpleTraceTable struct{}

func (table *_SimpleTraceTable) genKey(serviceInfo *trace_api.ServiceInfo, traceId string) []byte {
	name := strings.Join([]string{_SIMPLE_TRACE_NAME_SPACE, serviceInfo.ServiceName, serviceInfo.ServiceVersion, traceId}, "\t")
	return []byte(name)
}

func (table *_SimpleTraceTable) Insert(txn *badger.Txn, traceInfo *trace_api.TraceInfo, keepTraceDay uint) error {
	key := table.genKey(traceInfo.Service, traceInfo.TraceId)
	value, err := proto.Marshal(traceInfo)
	if err != nil {
		return err
	}
	entry := badger.NewEntry(key, value).WithTTL(time.Duration(keepTraceDay) * time.Hour * 24)
	return txn.SetEntry(entry)
}

func (table *_SimpleTraceTable) ListById(txn *badger.Txn, serviceInfo *trace_api.ServiceInfo, traceIdList []string) ([]*trace_api.TraceInfo, error) {
	traceList := []*trace_api.TraceInfo{}

	for _, traceId := range traceIdList {
		key := table.genKey(serviceInfo, traceId)
		item, err := txn.Get(key)
		if err != nil {
			if err == badger.ErrKeyNotFound {
				continue
			}
			return nil, err
		}
		if item.IsDeletedOrExpired() {
			continue
		}
		value, err := item.ValueCopy(nil)
		if err != nil {
			return nil, err
		}
		trace := &trace_api.TraceInfo{}
		err = proto.Unmarshal(value, trace)
		if err != nil {
			return nil, err
		}
		traceList = append(traceList, trace)
	}
	return traceList, nil
}
